#include "Connection.h"
#include <QByteArray>
#include <QTcpSocket>

using Networking::Connection;

Connection::Connection(QTcpSocket* sock) :
    m_socket(sock), m_descriptor(-1)
{
    qDebug() << "Connection::TcpConnection(QTcpSocket* sock)";
    connect(m_socket, SIGNAL(disconnected()),
            this, SIGNAL(SignalConnectionLost()));

    connect(m_socket, SIGNAL(readyRead()),
            this, SLOT(SlotReadData()));
}

void Connection::DisconnectFromHost()
{
    m_socket->disconnectFromHost();
}

Connection::~Connection()
{
    m_socket->deleteLater();
}

void Connection::SlotSendData(const QString& msg)
 {
    qDebug() << "void Connection::SlotSendData(const QString& msg)";
     m_socket->write(packMessage(msg));
 }

QByteArray Connection::packMessage(const QString& msg) const
{
     QByteArray packetData;
     QDataStream out(&packetData, QIODevice::WriteOnly);
     out.setVersion(QDataStream::Qt_4_8);
     out << quint16(0) << msg.toUtf8();
     out.device()->seek(0);
     out << quint16(packetData.size() - sizeof(quint16));

     return packetData;
}

void Connection::SlotReadData()
{
   qDebug() << "void Connection::SlotReadData()";
   QTcpSocket *socket = (QTcpSocket*)sender();
   quint16 m_nNextBlockSize = 0;
   QDataStream in(socket);
   in.setVersion(QDataStream::Qt_4_8);
   QString message;
   for (;;)
   {
       if (!m_nNextBlockSize)
       {
          if (socket->bytesAvailable() < sizeof(quint16))
          {
             break;
          }
          in >> m_nNextBlockSize;
       }
       if (socket->bytesAvailable() < m_nNextBlockSize)
       {
             break;
       }
       QByteArray data;
       in >> data;
       message = data;
       m_nNextBlockSize = 0;
    }
   if(!message.isEmpty())
   {
        emit SignalNewMessage(message, m_descriptor);
        qDebug() << "emit Connection::SignalNewMessage(" << message << ")";
   }
}/*
QString Connection::peerInfo() const
{
    return m_socket->peerAddress().toString() + m_socket->peerPort();
}*/
